package cn.shenshen.shop.resolve;

import cn.shenshen.shop.domain.User;
import cn.shenshen.shop.redis.MemberKeyPrefix;
import cn.shenshen.shop.redis.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * 自定义参数解析器
 */
@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver{

    @Autowired
    private RedisService redisService;

    //判断是否需要参数绑定
    public boolean supportsParameter(MethodParameter methodParameter) {
        //需要与注册这样的功能进行区分用到自定义注解的方式,这里就不实现了
        return methodParameter.getParameterType() == User.class;
    }

    //进行参数绑定
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookies.length==0){
            return null;
        }
        for (Cookie cookie : cookies) {
            if ("USER_TOKEN".equals(cookie.getName())){
                String token = cookie.getValue();
                User user = redisService.get(MemberKeyPrefix.USER_TOKEN, token, User.class);
                return user;
            }
        }
        return null;
    }
}
